package controller.business.companyAssess;

import base.response.OffsetLimitPage;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import controller.common.BaseController;
import controller.common.StaticConstant;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import response.CommonResult;
import services.business.BusinessInfoServices;
import services.business.CompanyAssessServices;
import services.business.InspectorInfoServices;
import util.DateUtil;
import util.io.UploadDownloadFileUtil;
import util.key.IDFactory;
import validator.NotBlankFluentValidator;
import validator.SizeFluentValidator;
import wt.entity.business.*;
import wt.staticData.ShortData;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能:
 * 作者: 洪世成
 * 日期: 2017/9/9
 * 版权所有: admin
 */
@Controller
@RequestMapping("business/companyAssess")
public class CompanyAssessController extends BaseController {
    @Autowired
    CompanyAssessServices companyAssessServices;
    @Autowired
    BusinessInfoServices businessInfoServices;
    @Autowired
    InspectorInfoServices inspectorInfoServices;


    @RequiresPermissions("business:companyAssess:default")
    @RequestMapping("index")
    public String index(Short companyIsAssess,Map map)
    {
        map.put("companyIsAssess",companyIsAssess);
        return "business/companyAssess/index";
    }


    @RequiresPermissions("business:companyAssess:default")
    @RequestMapping("editDlg")
    public String editDlg(String businessId, Map map) throws Exception {

        map.put("businessId", businessId);
        map.put(StaticConstant.EDIT_URL, "business/companyAssess/insert");
        map.put(StaticConstant.EDIT_OPERATE_TYPE, StaticConstant.EDIT_INSERT);
        return "business/companyAssess/editDlg";

    }

    @RequiresPermissions("business:companyAssess:default")
    @ResponseBody
    @RequestMapping("insert")
    public CommonResult insert(CompanyAssess companyAssess) throws Exception {
        CommonResult commonResult = CommonResult.newCommonResult();
        ComplexResult result = FluentValidator.checkAll().failOver()
                .on(companyAssess.getBusinessId(), new NotBlankFluentValidator("业务编号"))
                .on(companyAssess.getBribery(), new SizeFluentValidator(0, 1, "收受礼品"))
                .on(companyAssess.getPrivateThing(), new SizeFluentValidator(0, 1, "解决个人问题"))
                .on(companyAssess.getConsultation(), new SizeFluentValidator(0, 1, "参加公司咨询"))
                .on(companyAssess.getStyle(), new SizeFluentValidator(0, 1, "作风和秉公"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            commonResult.addMessage(result);
            return commonResult.setError();
        }

        if (companyAssess.getBribery() == 1 && StringUtils.isBlank(companyAssess.getBriberyRemark())) {
            commonResult.addMessage("收受礼品不能为空");
            return commonResult.setError();
        }
        if (companyAssess.getPrivateThing() == 1 && StringUtils.isBlank(companyAssess.getPrivateThingRemark())) {
            commonResult.addMessage("解决个人问题不能为空");
            return commonResult.setError();
        }

        if (companyAssess.getConsultation() == 1 && StringUtils.isBlank(companyAssess.getConsultationRemark())) {
            commonResult.addMessage("参加公司咨询不能为空");
            return commonResult.setError();
        }

        if (companyAssess.getStyle() == 1 && StringUtils.isBlank(companyAssess.getStyleRemark())) {
            commonResult.addMessage("作风和秉公不能为空");
            return commonResult.setError();
        }


        int conclusion = companyAssess.getBribery() + companyAssess.getConsultation() + companyAssess.getPrivateThing() + companyAssess.getStyle();
        companyAssess.setConclusion(conclusion >= 1 ? 1 : 0);
        companyAssess.setAssessTime(new Date());

        companyAssessServices.insertSelective(companyAssess,companyAssess.getBusinessId());
        return commonResult.setSuccess();
    }

    


    @RequiresPermissions("business:companyAssess:default")
    @ResponseBody
    @RequestMapping("select")
    public OffsetLimitPage select(
            String productName,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
            Short companyIsAssess,
            Integer offset,
            Integer limit
    ) throws Exception {

        BusinessInfoExample businessInfoExample = new BusinessInfoExample();
        BusinessInfoExample.Criteria criteria = businessInfoExample.createCriteria();
        businessInfoExample.setOrderByClause("id desc");
        criteria.andCompanyIdEqualTo(getLoginAccount().getCompanyInfo().getId()).andBusinessWorkFlowEqualTo(ShortData.s3);
        
        if (!StringUtils.isBlank(productName)) {
            criteria.andProductNameLike("%" + productName + "%");
        }

        if (startTime != null) {
            criteria.andEndTimeGreaterThanOrEqualTo(startTime);
        }

        if (endTime != null) {
            criteria.andEndTimeLessThan(DateUtil.moveDate(endTime, 1));
        }

        if (companyIsAssess != null) {
            criteria.andCompanyIsAssessEqualTo(companyIsAssess);
        }
        return businessInfoServices.selectByExample(businessInfoExample, offset, limit);
    }

    @RequiresPermissions("business:companyAssess:default")
    @ResponseBody
    @RequestMapping("welcomeTips")
    public CommonResult welcomeTips() throws Exception {
        CommonResult commonResult = new CommonResult();
        BusinessInfoExample businessInfoExample = new BusinessInfoExample();
        businessInfoExample.createCriteria().andCompanyIdEqualTo(getLoginAccount().getCompanyInfo().getId()).andCompanyIsAssessEqualTo(ShortData.s0);
        int count = businessInfoServices.countByExample(businessInfoExample);
        if (count == 0) {
            return commonResult.setError();
        } else {
            Map map = new HashMap();
            map.put("info", count + "份企业评价未填写");
            map.put("url", "business/companyAssess/index?companyIsAssess=0");
            commonResult.setData(map);
            return commonResult.setSuccess();
        }
    }



    @RequestMapping("pdf/{businessId}")
    public ResponseEntity<byte[]> pdf(HttpServletRequest request, @PathVariable("businessId") String businessId) throws Exception {

        BusinessInfo businessInfo = businessInfoServices.selectByPrimaryKey(businessId);

        CompanyAssessExample companyAssessExample = new CompanyAssessExample();
        companyAssessExample.createCriteria().andBusinessIdEqualTo(businessId);
        CompanyAssess companyAssess = companyAssessServices.selectByExample(companyAssessExample).get(0);

        List<InspectorInfo> inspectorInfoList = inspectorInfoServices.selectByBusinessId(businessId);
        String leaderName="",crewsName="";
        for (InspectorInfo inspectorInfo : inspectorInfoList) {
            if ("leader".equals(inspectorInfo.getExpertRole())){
                leaderName=inspectorInfo.getExpertName();
            }else{
                crewsName+=inspectorInfo.getExpertName()+"，";
            }
        }
        crewsName=crewsName.substring(0,crewsName.length()-1);//去除最后的“，”

        Map<String,String> map = new HashMap<String,String>();

        map.put("companyName", businessInfo.getCompanyName());
        map.put("checkTime",DateUtil.date2String(businessInfo.getEndTime(),"yyyy-MM-dd"));
        map.put("leader",leaderName);
        map.put("crew",crewsName);
        map.put("bribery",companyAssess.getBribery()==0?"无。":"有。");
        map.put("briberyRemark",companyAssess.getBriberyRemark());
        map.put("privateThing",companyAssess.getPrivateThing()==0?"无。":"有。");
        map.put("privateThingRemark",companyAssess.getPrivateThingRemark());
        map.put("consultation",companyAssess.getConsultation()==0?"无。":"有。");
        map.put("consultationRemark",companyAssess.getConsultationRemark());
        map.put("style", companyAssess.getStyle() == 0 ? "无。" : "有。");
        map.put("styleRemark",companyAssess.getStyleRemark());
        map.put("remark",companyAssess.getRemark());



        File file = FileUtils.getFile(FileUtils.getTempDirectory(), IDFactory.getSnowflakeId());
        CompanyAssessPdf.createPdf(FileUtils.openOutputStream(file), map);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        file.delete();


        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", UploadDownloadFileUtil.encodeChineseDownloadFileName("工作纪律情况反馈表.pdf", request));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

    }

    @RequestMapping("doc/{businessId}")
    public ResponseEntity<byte[]> doc(HttpServletRequest request, @PathVariable("businessId") String businessId) throws Exception {

        BusinessInfo businessInfo = businessInfoServices.selectByPrimaryKey(businessId);

        CompanyAssessExample companyAssessExample = new CompanyAssessExample();
        companyAssessExample.createCriteria().andBusinessIdEqualTo(businessId);
        CompanyAssess companyAssess = companyAssessServices.selectByExample(companyAssessExample).get(0);

        List<InspectorInfo> inspectorInfoList = inspectorInfoServices.selectByBusinessId(businessId);
        String leaderName="",crewsName="";
        for (InspectorInfo inspectorInfo : inspectorInfoList) {
            if ("leader".equals(inspectorInfo.getExpertRole())){
                leaderName=inspectorInfo.getExpertName();
            }else{
                crewsName+=inspectorInfo.getExpertName()+"，";
            }
        }
        crewsName=crewsName.substring(0,crewsName.length()-1);//去除最后的“，”

        Map<String,String> map = new HashMap<String,String>();

        map.put("companyName", businessInfo.getCompanyName());
        map.put("checkTime",DateUtil.date2String(businessInfo.getEndTime(),"yyyy-MM-dd"));
        map.put("leader",leaderName);
        map.put("crew",crewsName);
        map.put("bribery",companyAssess.getBribery()==0?"无。":"有。");
        map.put("briberyRemark",companyAssess.getBriberyRemark());
        map.put("privateThing",companyAssess.getPrivateThing()==0?"无。":"有。");
        map.put("privateThingRemark",companyAssess.getPrivateThingRemark());
        map.put("consultation",companyAssess.getConsultation()==0?"无。":"有。");
        map.put("consultationRemark",companyAssess.getConsultationRemark());
        map.put("style", companyAssess.getStyle() == 0 ? "无。" : "有。");
        map.put("styleRemark",companyAssess.getStyleRemark());
        map.put("remark",companyAssess.getRemark());


        File file = FileUtils.getFile(FileUtils.getTempDirectory(), IDFactory.getSnowflakeId());
        CompanyAssessDoc.createDoc(FileUtils.openOutputStream(file), map);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        file.delete();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", UploadDownloadFileUtil.encodeChineseDownloadFileName("工作纪律情况反馈表.doc", request));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

    }

}
